package com.ldy.gkrpc.transport.impl;

import com.ldy.gkrpc.proto.Peer;
import com.ldy.gkrpc.transport.TransportClient;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description
 * @Author songxulin
 * @Date 2020/4/12 17:36
 **/
public class HTTPTransportClient implements TransportClient {
    private String url;
    @Override
    public void connect(Peer peer) {
        this.url = "http://"+peer.getHost()+":"+peer.getPort();
    }

    @Override
    public InputStream write(InputStream data) {
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
            //输出数据
            httpURLConnection.setDoOutput(true);
            //读数据
            httpURLConnection.setDoInput(true);
            //不要缓存
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.connect();

            IOUtils.copy(data, httpURLConnection.getOutputStream());
            int responseCode = httpURLConnection.getResponseCode();
            if(responseCode ==HttpURLConnection.HTTP_OK){
                return httpURLConnection.getInputStream();
            }else {
                return httpURLConnection.getErrorStream();
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void close() {

    }
}
